<?php
/**
* @package YaForms
* @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
* @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
* YaForms! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
* Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
*/

defined( '_VALID_MOS' ) or die( 'Restricted access' );


function stripData( $data ){

   return ini_get('magic_quotes_gpc') ? stripslashes($data) : $data;

}

//радиокнопка
function afRadioList( &$arr, $tag_name, $tag_attribs, $selected=null, $key='value', $text='text' ){

     reset( $arr );
     $html = "";
     for ($i=0, $n=count( $arr ); $i < $n; $i++ )
     {
	$k = $arr[$i]->$key;
	$t = $arr[$i]->$text;
	$id = isset($arr[$i]->id) ? $arr[$i]->id : null;
	$extra = '';
	$extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
	if (is_array( $selected ))
        {
           foreach ($selected as $obj)
           {
	      $k2 = $obj->$key;
              if ($k == $k2)
              {
	         $extra .= " checked=\"checked\"";
	         break;
	      }
	   }
        } else {
	   $extra .= ($k == $selected ? " checked=\"checked\"" : '');
	}
	   $html .= "\n\t<input type=\"radio\" name=\"$tag_name\" value=\"".$k."\"$extra $tag_attribs />\n ".$t."<br />\n";
     }
     $html .= "\n";
     return $html;
     
}

//флажки или галочки
function afCheckboxList( &$arr, $tag_name, $tag_attribs, $selected=null, $key='value', $text='text' ){

     reset( $arr );
     $html = "";
     $tagNcount = "0";
     for ($i=0, $n=count( $arr ); $i < $n; $i++ )
     {
        $k = $arr[$i]->$key;
        $t = $arr[$i]->$text;
        $id = isset($arr[$i]->id) ? $arr[$i]->id : null;
	$extra = '';
	$extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
	if (is_array( $selected ))
        {
	   foreach ($selected as $obj)
           {
	      $k2 = $obj->$key;
	      if ($k == $k2)
              {
		 $extra .= " checked=\"checked\"";
		 break;
	      }
	   }
	} else {
	   $extra .= ($k == $selected ? " checked=\"checked\"" : '');
	}

	$tag_n=$tag_name.'['.$tagNcount.']';
	$html .= "\n\t<input type=\"checkbox\" name=\"$tag_n\" value=\"".$k."\" $extra $tag_attribs />\n ".$t."<br />";
	$tagNcount=$tagNcount+1;
     }

     $html .= "\n";
     return $html;
     
}

//выпадающий список
function afSelectList( &$arr, $tag_name, $tag_attribs, $key, $text, $selected=NULL ){

     reset( $arr );
     $html = "\n<select name=\"$tag_name\" $tag_attribs>";
     for ($i=0, $n=count( $arr ); $i < $n; $i++ )
     {
        $k = $arr[$i]->$key;
        $t = $arr[$i]->$text;
        if ( 'size="1"' === $tag_attribs ){
        $value = $t;
        } else {
        $value = $k;
        }
        $id = isset($arr[$i]->id) ? $arr[$i]->id : null;
        $extra = '';
        $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
        if (is_array( $selected ))
        {
           foreach ($selected as $obj)
           {
              $k2 = $obj->$key;
              if ($k == $k2)
              {
                 $extra .= " selected=\"selected\"";
                 break;
              }
           }
	} else {
           $extra .= ($k == $selected ? " selected=\"selected\"" : '');

        }
        $html .= "\n\t<option value=\"".trim($value)."\"$extra>\n" . $t . "</option>";
     }
     $html .= "\n</select>\n";
     return $html;

}

//валидация мыла
function validate_email( $email ){

   global $Itemid, $mosConfig_fromname, $mosConfig_mailfrom;
   $regExp="^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,4})$";
   if (ereg($regExp, $email)){
      return true;
   }
   return false;
     
}


function afHitCounter( $formid ){

   global $database;
   $database->setQuery("UPDATE #__yaforms SET hits=hits+1 WHERE id=".$formid );
   $database->query();
      
}
   
//сохраняем форму в БД 
function saveDBForms( &$database, $option, $name, $data, $formtitle, $formid ) {

   require_once( JPATH_BASE.'/administrator/components/com_yaforms/yaforms.class.php' );

   $row = new mosyaforms_inbox( $database );

   $date_time = date( YAF_DATETIME );

   $row->title     = $formtitle;
   $row->form_id   = $formid;
   $row->item_name = $name;
   $row->item_data = $data;
   $row->form_date = $date_time;

   // Связать значения в ряд
   if (!$row->bind( $_POST )) {
      return $database->getErrorMsg();
   }

   // Установить первичный ключ
   $row->_tbl_key = "id";

   if (!$row->store()) {
      return $database->getErrorMsg();
   }

   return NULL;

}

//дата создания
function afCreateDate( &$row, &$params ) {

   $create_date = null;

   if ( intval( $row->created ) != 0 ) $create_date = mosFormatDate( $row->created );

   if ( $params->get( 'show_created_date' ) ) {

      $html = '<div align="right" class="createdate">
	       '.$create_date.'
	       </div>';
      return $html;

   } else {

      return;

   }
   
}
//дата модификации
function afModifiedDate( &$row, &$params ) {

   $mod_date = null;
   if( intval( $row->modified ) != 0)$mod_date = mosFormatDate( $row->modified );

   if ( ( $mod_date != '' ) && $params->get( 'show_modif_date' ) ) {

      $html = '<div align="right" class="modifydate">
	       '.Y_LAST_UPDATED.' ( '.$mod_date.' )
	       </div>';
      return $html;

   } else {

      return;

   }
   
}

//автор
function afAuthor( &$row, &$params ) {

   if ( ( $params->get( 'show_author' ) ) && ( $row->author != '' ) ) {

      $html = '<br />
               <div align="right" valign="top" colspan="2">
               <span class="small">
               '._WRITTEN_BY . ' '.( $row->created_by_alias ? $row->created_by_alias : $row->author ).'
               </span>
               </div>';
      return $html;

   } else {

      return;

   }
   
}

//кнопка назад
function afBackBtn( &$params ) {

   if( $params->get( 'show_back_button' ) == '1' ){

      $html = '<br />
               <div class="back_button">
               <a href="javascript:history.go(-1)">'._BACK.'</a>
               </div>';
      return $html;
      
   } else {
   
      return;
      
   }
  
}


function afMakeFieldName( $item, $a_error_ids='' ) {

   if( $item->type == '8' || $item->type == '10' ) return;

   $fieldname = '';
   
   if(in_array($item->item_id, $a_error_ids))$fieldname .= '<div class="yaforms-errorftxt">';
   $fieldname .= '<div class="affieldname">'.$item->name.': </div>';
   if(in_array($item->item_id, $a_error_ids))$fieldname .= '</div>';
   
   return $fieldname;
	        
}


function afMakeField( $item, $rowhtml='0', $afhtmleditor='tinymce_light' ) {

   $value = '';
   if( $item->readonly == '1' ) {
      $readonly = ' readonly="true"';
   } else {
      $readonly = '';
   }
   if( $item->customcode != '' ) {
      $customcode = ' '.$item->customcode;
   } else {
      $customcode = '';
   }
   $item->values = str_replace("&lt;","<",$item->values);
   $item->values = str_replace("&gt;",">",$item->values);
   $item->default_values = str_replace("&lt;","<",$item->default_values);
   $item->default_values = str_replace("&gt;",">",$item->default_values);
   
   switch ( $item->type ) {

      case '1': //Простое поле
         if(isset($_POST['item_'.$item->item_id])){
            $value = $_POST['item_'.$item->item_id];
         } else {
            $value = $item->default_values;
         }
         $field = '<input type="text" name="item_'.$item->item_id.'" size="35" maxlength="70" value="'.$value.'"'.$readonly.$customcode.' />';
         return $field;
      break;

      case '2': //Текстовое поле
         $field = '';
         if ($rowhtml=='1'){
            $field .= '<div align="center" class="yaformstextarea-html">';
            if(isset($_POST['item_'.$item->item_id])){
               $value = $_POST['item_'.$item->item_id];
            } else {
               $value = $item->default_values;
            }
            include(JPATH_BASE.'/components/com_yaforms/includes/editors/'.$afhtmleditor.'.php');
            $field .= '<textarea class="inputboxhtml" name="item_'.$item->item_id.'" id="item_'.$item->item_id.'" cols="60" rows="15"'.$readonly.$customcode.'>'.$value.'</textarea>';
            $field .= afHtmlEditor( YAF_EDITORLANG, YAF_LANGDIRECTION, 'item_'.$item->item_id );
            $field .= '</div>'.YAF_HTMLON;
         } else {
            $field .= '<div align="center" class="yaformstextarea-txt">
                          <textarea class="inputboxtxt" name="item_'.$item->item_id.'" cols="40" rows="10"'.$readonly.$customcode.'>'.$value.'</textarea>
                       </div>';
         }
         return $field;
      break;
      
      case '3': //Список
         $item_values = array();
         $item_default_values = array();
         if($item->values!=''){
            $tmp = explode(';', $item->values);
            $tmp_default = explode(';', $item->default_values);
            foreach($tmp as $key => $tmp_item){
               $item_values[] = mosHTML::makeOption( $key, $tmp_item);
               if(isset($_POST['do']) && isset($_POST['item_'.$item->item_id])){
                  $posted_value = $_POST['item_'.$item->item_id];
                  if(is_array($posted_value)){
                     if(in_array($key, $posted_value))$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
                  } else {
                     if($key == $posted_value)$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
                  }
               } else {
                  if(in_array($tmp_item, $tmp_default))$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
               }
            }
         }
	 $html_attr = "\n\n";
	 $field = afRadioList( $item_values, 'item_'.$item->item_id, $html_attr, $item_default_values, 'value', 'text');
         return $field;
      break;
      
      case '4': //Чекбокс
         $item_values = array();
         $item_default_values = array();
         if($item->values!=''){
            $tmp = explode(';', $item->values);
            $tmp_default = explode(';', $item->default_values);
            foreach($tmp as $key => $tmp_item){
               $item_values[] = mosHTML::makeOption( $key, $tmp_item);
               if(isset($_POST['do']) && isset($_POST['item_'.$item->item_id])){
                  $posted_value = $_POST['item_'.$item->item_id];
                  if(is_array($posted_value)){
                     if(in_array($key, $posted_value))$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
                  } else {
                     if($key == $posted_value)$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
                  }
               } else {
                  if(in_array($tmp_item, $tmp_default))$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
               }
            }
         }
         $html_attr = "\n\n";
         $field = afCheckboxList( $item_values, 'item_'.$item->item_id, $html_attr, $item_default_values, 'value', 'text');
         return $field;
      break;
      
      case '5': //Выпадающий список
         $item_values = array();
         $item_default_values = array();
         if($item->values!=''){
            $tmp = explode(';', $item->values);
            $tmp_default = explode(';', $item->default_values);
            foreach($tmp as $key => $tmp_item){
               $item_values[] = mosHTML::makeOption( $key, $tmp_item);
               if(isset($_POST['do']) && isset($_POST['item_'.$item->item_id])){
                  $posted_value = $_POST['item_'.$item->item_id];
                  if(is_array($posted_value)){
                     if(in_array($key, $posted_value))$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
                  } else {
                     if($key == $posted_value)$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
                  }
               } else {
                  if(in_array($tmp_item, $tmp_default))$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
               }
            }
         }
         $html_attr = 'size="1"';
         $field = afSelectList( $item_values, 'item_'.$item->item_id, $html_attr, 'value', 'text', $item_default_values);
         return $field;
      break;
      
      case '6': //Выпадающий список мультивыбор
         $item_values = array();
         $item_default_values = array();
         if($item->values!=''){
            $tmp = explode(';', $item->values);
            $tmp_default = explode(';', $item->default_values);
            foreach($tmp as $key => $tmp_item){
               $item_values[] = mosHTML::makeOption( $key, $tmp_item);
               if(isset($_POST['do']) && isset($_POST['item_'.$item->item_id])){
                  $posted_value = $_POST['item_'.$item->item_id];
                  if(is_array($posted_value)){
                     if(in_array($key, $posted_value))$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
                  } else {
                     if($key == $posted_value)$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
                  }
               } else {
                  if(in_array($tmp_item, $tmp_default))$item_default_values[] = mosHTML::makeOption( $key, $tmp_item );
               }
            }
         }
         $listHeight = '8';
         if(count($item_values)<10)$listHeight = '4';
         
         $html_attr = 'size="'.$listHeight.'" multiple="multiple"';
         $field = afSelectList( $item_values, 'item_'.$item->item_id.'[]', $html_attr, 'value', 'text', $item_default_values);
         return $field;
      break;
      
      case '7': //Date Field
         if(isset($_POST['item_'.$item->item_id])){
            $value = $_POST['item_'.$item->item_id];
         } else {
            $value = $item->default_values;
         }
         $field = '<div class="yaforms-date">
                      <input type="text" name="item_'.$item->item_id.'" id="item_'.$item->item_id.'" value="'.$value.'" size="10" maxlength="15"'.$readonly.$customcode.' />
		      <input type="reset" class="yaforms-button" name="reset" value="'.YAF_DATEBTN.'" onclick="return showCalendar(\'item_'.$item->item_id.'\', \'mm-dd-Y\');" />
                   </div>';
         return $field;
      break;
      
      case '8': //HTML Code
	 $field = $item->default_values.'
		      <input type="hidden" name="item_'.$item->item_id.'" value="-" />';
         return $field;
      break;
      
      case '9': //Textarea -plain text-
         if(isset($_POST['item_'.$item->item_id])){
            $value = $_POST['item_'.$item->item_id];
         } else {
            $value = $item->default_values;
         }
         $field = '<div class="yaformstextarea-txt">
                      <textarea class="inputboxtxt" name="item_'.$item->item_id.'" cols="40" rows="10"'.$readonly.$customcode.'>'.$value.'</textarea>
                   </div>';
         return $field;
      break;
      
      case '10': //Скрытое поле
         if(isset($_POST['item_'.$item->item_id])){
            $value = $_POST['item_'.$item->item_id];
         } else {
            $value = $item->default_values;
         }
         $field = '<input type="hidden" name="item_'.$item->item_id.'" value="'.$value.'"'.$readonly.$customcode.' />';
         return $field;
      break;
      
      case '11': //Pasword input
         if(isset($_POST['item_'.$item->item_id])){
            $value = $_POST['item_'.$item->item_id];
         } else {
            $value = $item->default_values;
         }
         $field = '<div class="yaforms-password">
                      <input type="password" name="item_'.$item->item_id.'" size="35" maxlength="70" value="'.$value.'"'.$readonly.$customcode.' />
                   </div>';
         return $field;
      break;
      
      case '12': //Password input with checker
         if(isset($_POST['item_'.$item->item_id][0])){
            $valuea = $_POST['item_'.$item->item_id][0];
         } else {
            $valuea = $item->default_values;
         }
         if(isset($_POST['item_'.$item->item_id][1])){
            $valueb = $_POST['item_'.$item->item_id][1];
         } else {
            $valueb = $item->default_values;
         }
         $field = '<div class="yaforms-password">
                      <input type="password" name="item_'.$item->item_id.'[0]" size="35" maxlength="70" value="'.$valuea.'"'.$readonly.$customcode.' />
                      <br />
                      <input type="password" name="item_'.$item->item_id.'[1]" size="35" maxlength="70" value="'.$valueb.'"'.$readonly.$customcode.' />
                   </div>';
         return $field;
      break;

   }

}


function afCheckFieldReq( $itemreq, $afcfg_asteriskimg='' ) {

   if ( $itemreq == '2' ){

      $asterisk = '&nbsp;&nbsp;<img border="0" src="'.JPATH_SITE.'/images/yaforms/asterisks/'.$afcfg_asteriskimg.'" alt="*" title="" />';
      return $asterisk;

   } else {

      return;

   }

}


function afPerformFields( $itemlayout, $fieldname, $thefield, $asterisk='' ) {

   if($itemlayout == ''){
      $itemlayout = '<div class="afvalue">
                        <div class="afvalue_1">###FIELDNAME###</div>
                        <div class="afvalue_2">###THEFIELD###</div>
                        <div class="afvalueasterix">###ASTERISK###</div>
                     </div>
                     <div class="clear"></div>';
   }
   
   $itemlayout = str_replace("&lt;","<",$itemlayout);
   $itemlayout = str_replace("&gt;",">",$itemlayout);
   
   $itemlayout = str_replace( "###FIELDNAME###" , $fieldname, $itemlayout );
   $itemlayout = str_replace( "###THEFIELD###" , $thefield, $itemlayout );
   $itemlayout = str_replace( "###ASTERISK###" , $asterisk, $itemlayout );
                
   return $itemlayout;

}


function afEmailCopy( $checker ) {

   if ( $checker !='0' ){
      $html = '<div id="af-emailcopy">
                  '.YAF_EMAILCOPY.'  '.'
		  <input name="email_copy" value="1" type="checkbox" />
               </div>';
      return $html;
   } else {
      return;
   }

}


function afShowRequirer( $reqchecker, $astimg ) {
   
   $reqchecker = substr($reqchecker,0,-1);
   $reqchecker = explode(',', $reqchecker);
	           
   if (in_array('2', $reqchecker)){
      $html = '<div id="yaforms-reqtext">
                  <img border="0" src="'.JPATH_SITE.'/images/yaforms/asterisks/'.$astimg.'" alt="*" title="" />
                  '.YAF_REQINFTEXT.'
               </div>';
      return $html;
   } else {
      return;
   }

}


function afShowButtons( $resetchecker ) {

   $html = '<div id="yaforms-buttons" style="width:100%;text-align:right;">
            <input class="yaforms-button" type="submit" name="submit" value="'.YAF_SEND.'" />';

   if( $resetchecker == '1' ){
      $html .= '   <input class="yaforms-button" type="reset" value="'.YAF_RESET.'" />';
   }

   $html .= '</div>';

   return $html;

}


function afDoCaptchasInForm( $captchasel ) {

   include( JPATH_BASE.'/administrator/components/com_yaforms/config.yaforms.php' );
   
   if( $captchasel == '0' )return;
   
   switch ( $captchasel ) {

      case '1': //adapted alikon captcha

         $html = '<div class="yf_field">';

         $html .= af_captcha_image();
         $html .= '</div><div class="yf_clear"></div>';
         return $html;
         
      break;
	  default:

         $html = '<div align="center">';
         $html .= YAF_CAPTCHA_NOTDEFINED;
         $html .= '</div>';
         return $html;
         
      break;
      
   }
   
   $html .= '</div>';

   return $html;

}


function afMakeNewsletterBridge( $newsletter ) {

   if( $newsletter == '0' || $newsletter == '' )return;
   
   switch ( $newsletter ) {

      case 'letterman': //adapted alikon captcha
         if( file_exists(JPATH_BASE.'/components/com_letterman/letterman.php')) {

            $html = '<div id="afnewsletter">
                        '.YAF_SUBSCRIPTTONL.'<br />
                        <input name="afnewsletter" value="1" checked="checked" type="radio">
	                '.YAF_MULTI_YES.'
	                <input name="afnewsletter" value="0"type="radio">
	                '.YAF_MULTI_NO.'
                     </div>';
            $html .= mosGetParam( $_POST, 'afnewsletter' );
            return $html;
      
         } else {
            return;
         }
         
      break;
   
   }

}


function afMakeNewsletterBridgeToDB( $newsletter, $user_id, $user_name, $user_email  ) {

   global $database, $mosConfig_lang;

   if( $newsletter == '0' || $newsletter == '' )return;

   switch ( $newsletter ) {

      case 'letterman': //Letterman's Newsletter Component

         if( file_exists(JPATH_BASE.'/components/com_letterman/letterman.php')) {
            require_once( JPATH_BASE.'/components/com_letterman/letterman.class.php');
            $row = new mosLettermanSubscribers($database);
            $row->subscriber_id = '';
 	    $row->user_id = $user_id;
 	    $row->subscriber_name = $user_name;
 	    $row->subscriber_email = $user_email;
	    $row->subscribe_date = date( 'Y-m-d H:i:s' );
            if (!$row->store()) {
                if( !@include( JPATH_BASE.'/administrator/components/com_letterman/language/'.$mosConfig_lang.'.messages.php' ) ) {
                   include( JPATH_BASE.'/administrator/components/com_letterman/language/english.messages.php' );
                }
                echo "<script type=\"text/javascript\"> alert('".LM_SAME_EMAIL_TWICE."');</script>\n";
	    }

         }

      break;

   }

}


?>
